package com.zlm.spider.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.UUID;

/**
 * @author Harbour
 * @date 2021-04-12 13:19
 */
@Component
public class HttpUtils {

    private final PoolingHttpClientConnectionManager pm = HttpClientsUtils.getHttpClientsPoolManager();
    private final Properties properties = PropertiesUtils.getProperties("application.properties");


//    public JSONObject getJSONObject(String url, String id) {
//        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pm).build();
//        HttpPost httpPost =
//    }

    /**
     * 获取 HTML 内容
     * @param url 地址
     * @return 返回一个html字符串
     */
    public String getHtml(String url) {
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pm).build();

        HttpGet httpGet = requestGet(url);

        CloseableHttpResponse response = null;
        try {
            // 使用HttpClient发起请求，返回response
            response = httpClient.execute(httpGet);
            // 解析response返回数据
            if (response.getStatusLine().getStatusCode() == 200) {
                String html = "";
                // 如果response.getEntity获取的结果是空，在执行EntityUtils.toString会报错
                if (response.getEntity() != null) {
                    html = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
                return html;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(response);
        }

        return null;
    }

    //获取图片
    public String getImage(String url) {
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pm).build();

        HttpGet httpGet = requestGet(url);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            // 解析response下载图片
            if (response.getStatusLine().getStatusCode() == 200) {

                String path = properties.getProperty("img.path");
                String extName = url.substring(url.lastIndexOf(".")); // 获取文件类型
                String imageName = UUID.randomUUID().toString() + extName; // 使用uuid生成图片名
                OutputStream out = new FileOutputStream(path + imageName); // 声明输出的文件
                response.getEntity().writeTo(out); // 使用响应体输出文件

                // 返回生成的图片名
                return imageName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(response);
        }

        return null;
    }

    //获取请求参数对象
    private RequestConfig getConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(5000) // 设置连接超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000) // 设置请求超时时间(单位毫秒)
                .setSocketTimeout(5000) // socket读写超时时间(单位毫秒)
                .setRedirectsEnabled(true)
                .build(); // 设置是否允许重定向(默认为true)

    }

    private HttpGet requestGet(String url) {
        // 声明httpGet请求对象
        HttpGet httpGet = new HttpGet(url);
        // 设置请求参数RequestConfig
        httpGet.setConfig(this.getConfig());
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0");
        return httpGet;
    }

    private void close(CloseableHttpResponse response) {
        try {
            if (response != null) response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
